#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <net/route.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/if.h>
#include "cgic.h"

static char gs_ipaddr[50] = "192.168.0.147";
static char html_buf[10240];

int cgiMain()
{
    FILE *fhtm = NULL;
    char *request_method = NULL;
    char *user_input = NULL;
    int test_udp_fd = -1;

    test_udp_fd = socket(AF_INET, SOCK_DGRAM, 0);
    struct sockaddr_in nsockaddr;
    nsockaddr.sin_family = AF_INET;
    nsockaddr.sin_port = htons(2305);
    nsockaddr.sin_addr.s_addr = inet_addr("192.168.0.198");

    fhtm = fopen("../www/sysconfig.html", "r");
    fread(html_buf, 1, 10240, fhtm);
    fclose(fhtm);

  //  printf("Content-type:text/html;charset=utf-8\n\n");
    cgiHeaderContentType("text/html");
    request_method = getenv("REQUEST_METHOD");
    if (strcmp(request_method, "GET") == 0)
    {
        user_input = getenv("QUERY_STRING");
        if (strcmp(user_input, "getsysconfig") == 0)
        {
            //向HTML传递参数
            fprintf(cgiOut, "IPAddr=%s/", gs_ipaddr);
            fprintf(cgiOut, "MaskIP=%s/", "255.255.255.0");
            fprintf(cgiOut, "GatewayIP=%s/", "192.168.0.1");
            fprintf(cgiOut, "Mac=%s/", "00:30:1B:BA:02:DB");
            fprintf(cgiOut, "readend");
        }
    }
    else if (strcmp(request_method, "POST") == 0)
    {
        cgiFormString("setIPAddr", gs_ipaddr, sizeof(gs_ipaddr));
        /* 将收到的数据通过UDP发送用来测试参数是否正确 */
        sendto(test_udp_fd, gs_ipaddr, sizeof(gs_ipaddr), 0,&nsockaddr, sizeof(nsockaddr));

        fprintf(cgiOut, html_buf);
    }
    close(test_udp_fd);

    return 0;
}